package cn.fsw.pethome.loginutil;

import cn.fsw.pethome.jwt.JwtUtils;
import cn.fsw.pethome.jwt.Payload;
import cn.fsw.pethome.jwt.PayloadData;
import cn.fsw.pethome.jwt.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

//登录上下文，把登录的相关信息放到这里面，方便调用
// 问题1：不受spring管理的类，想要获取受spring管理的bean 只要获取到spring容器就可以从容器中获取
@Slf4j
@Component
public class LoginContextUtils {

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPub;
    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;

    /**
     *
     * @param request
     * @return 如果是后台需要返回employee，如果是前台返回user
     */
    public  Object getLoginUser(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token))
                return null;
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            //解密
            //通过公钥解析token，登陆载荷体
            Payload<PayloadData> payload = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
            PayloadData payloadData = payload.getUserInfo();
            if (payloadData!=null){
            return payloadData.getUser()!=null?payloadData.getUser():payloadData.getAdmin();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}